package com.py.pythink.service.impl;

import com.py.pythink.bo.SmsCodeBo;
import com.py.pythink.config.RedisKeyConfig;
import com.py.pythink.config.SystemConfig;
import com.py.pythink.dao.SmslogDao;
import com.py.pythink.entity.SmsLog;
import com.py.pythink.service.intf.SmslogService;
import com.py.pythink.third.AliSmsUtil;
import com.py.pythink.third.JedisUtil;
import com.py.pythink.util.NumUtil;
import com.py.pythink.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SmslogServiceImpl implements SmslogService {
    @Autowired
    private SmslogDao dao;
    int code;
    @Override
    public R sendCode(String phone) {
        String key = RedisKeyConfig.CODE_R+phone;
        if(JedisUtil.checkKey(key)){//这个只是验证是否给你一个新的验证码
            if(JedisUtil.ttl(key)> RedisKeyConfig.CODE_R_TIME/2){
                 code = Integer.parseInt(JedisUtil.getStr(key));
            }else{
                code = NumUtil.getNums(SystemConfig.CODE_LEN);
            }
        }else{
            code = NumUtil.getNums(SystemConfig.CODE_LEN);
        }

        if(AliSmsUtil.sendLoginCode(phone,code)){
            JedisUtil.addStr(key,code+"",RedisKeyConfig.CODE_R_TIME);
            dao.insert(new SmsLog(phone,SystemConfig.SMS_TYPE_1,"验证码注册",new Date()));

            return R.ok();
        }
        return R.fail();
    }

    @Override
    public R sendCodeLogin(String phone) {
        String key = RedisKeyConfig.CODE_L+phone;
        if(JedisUtil.checkKey(key)){
            if(JedisUtil.ttl(key)> RedisKeyConfig.CODE_R_TIME/2){
                code = Integer.parseInt(JedisUtil.getStr(key));
            }else{
                code = NumUtil.getNums(SystemConfig.CODE_LEN);
            }
        }else{
            code = NumUtil.getNums(SystemConfig.CODE_LEN);
        }
        if(AliSmsUtil.sendRegisterCode(phone,code)){
            JedisUtil.addStr(key,code+"",RedisKeyConfig.CODE_R_TIME);
            dao.insert(new SmsLog(phone,SystemConfig.SMS_TYPE_2,"验证码登陆",new Date()));

            return R.ok();
        }
        return R.fail();

    }

    @Override
    public R checkCode(SmsCodeBo smsCodeBo) {
        String key = RedisKeyConfig.CODE_R+smsCodeBo.getPhone();
        if(JedisUtil.checkKey(key)){
            if(smsCodeBo.getCode()==Integer.parseInt(JedisUtil.getStr(key))){
                JedisUtil.delStr(key);
                return R.ok();
            }
        }
        return R.fail();

    }

    @Override
    public R selectAll() {
        return R.ok(dao.selectList(null));
    }
}
